<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:users:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:users:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:users:remove']"
        >删除</el-button>
      </el-col>
      
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户的唯一标识" align="center" prop="userid" sortable />
      <el-table-column label="用户姓名" align="center" prop="name" />
      <el-table-column label="用户名，需唯一" align="center" prop="username" />
      <el-table-column label="入职时间" align="center" prop="startdate" sortable/>
      <el-table-column label="职位" align="center" prop="position" />
      <el-table-column label="电话" align="center" prop="phone" sortable/>
      <el-table-column label="薪资" align="center" prop="salary" />

      <el-table-column label="用户邮箱" align="center" prop="email" />

      
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="用户角色" align="center" prop="role" />
      <el-table-column label="部门id" align="center" prop="departmentid" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:users:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:users:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    

    
    <el-pagination      
  :total="total"
  v-model:currentPage="queryParams.pageNum"
  v-model:pageSize="queryParams.pageSize"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"
  layout="total, sizes, prev, pager, next, jumper"
/>

    <!-- 添加或修改存储系统用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body :close-on-click-modal="false"
    destroy-on-close>
      <el-form ref="usersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名，需唯一" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="入职日期" prop="startdate">
   
      
      <el-date-picker
       v-model="form.startdate"
        type="datetime"
        placeholder="Select date and time"
        style="width: 500px;"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="MMM DD, YYYY"
        time-format="HH:mm"
      />
    
  </el-form-item>
        <el-form-item label="职位" :label-width="formLabelWidth">
                <el-select v-model="form.position" placeholder="请选择是否完成">
                  <el-option v-for="item in positionsOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>


        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
 <el-form-item label="薪资" prop="salary">
          <el-input v-model="form.salary" placeholder="请输入密码" />
        </el-form-item>
 <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入密码" />
        </el-form-item> 
      <el-form-item label="用户角色" prop="role">
              <el-select
            v-model="form.role"
            placeholder="请选择用户角色"
            size="large"
            style="height: auto; width: 500px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> 
       

        <el-form-item label="部门" :label-width="formLabelWidth">
                <el-select v-model="form.departmentid" placeholder="请选择部门成">
                  <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Users" >
import { getCurrentInstance,ref,reactive,toRefs} from 'vue';
import { listUsers, getUsers, delUsers, addUsers, updateUsers } from "@/api/system/users";
import { ElMessage ,ElMessageBox} from 'element-plus';
import axios from 'axios';
// 使用 ElMessage
const { proxy } = getCurrentInstance();
const queryRef = ref(null); // 定义 ref 引用

const usersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 时间选择器
const value1 = ref('')
const defaultTime = new Date(2000, 1, 1, 12, 0, 0)
const shortcuts = [
  {
    text: 'Today',
    value: new Date(),
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    },
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    },
  },
]

// 角色选择器
const options = [
  {
    value: '1',
    label: '管理员',
  },
  {
    value: '2',
    label: '部门管理员',
  },
  {
    value: '3',
    label: '员工',
  }
  
]



const data = reactive({
  form: {
    userid: null,
    name: '',       // 使用空字符串而不是 null
    username: '',
    password: '',
    role: '',
    startdate: '',
    position: '',
    phone: '',
    salary: '',
    email: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize:10,
    name: null,
    username: null,
    password: null,
    startdate: null,
    position: null,
    email: null,
    phone: null,
    salary: null,
    role: null,
    departmentid: null

  },
  
  rules: {
    name: [
      { required: true, message: "用户姓名不能为空", trigger: "blur" }
    ],
    username: [
      { required: true, message: "用户名，需唯一不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    role: [
      { required: true, message: "用户角色不能为空", trigger: "blur" }
  ],
    position: [
      { required: true, message: "职位不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
// 分页



//获取部门

const departmentOptions = reactive([]);

const fetchdepartmentOptions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/system/department/select');
    const departments = response.data.data;
    console.log(response.data)
    console.log("departments",departments)
    // 更新分类数据
    departments.forEach(department => {
      // 假设你的下拉菜单使用的是el-option
      departmentOptions.push({
        label: department.departmentname,
        value: department.departmentid

      });
    });
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
};


//获取职位

const positionsOptions = reactive([]);

const fetchpositionsOptions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/system/positions/lists');
    const positions = response.data.data;
    console.log(response.data)
    console.log("positions",positions)
    // 更新分类数据
    positions.forEach(position => {
      // 假设你的下拉菜单使用的是el-option
      positionsOptions.push({
        label: position.positionname,
        value: position.positionname

      });
      console.log("positionsOptions",positionsOptions)
    });
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
};



console.log("")
/** 查询存储系统用户信息列表 */
function getList() {
  loading.value = true;
  // let str = sessionStorage.getItem("user")
  
  // if(str){
  //   const parsedQueryParams=JSON.parse(str)
  //   queryParams.value={
  //     ...queryParams.value,
  //     ...parsedQueryParams
  //   }
  // }
  listUsers(queryParams.value).then(response => {
    usersList.value = response.list;
    console.log("response.list",response.list)
    console.log("response",response)
    total.value = response.total;
    console.log("tota.value",total.value)
    console.log("getList",getList)
    loading.value = false;
    console.log(usersList.value)
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
const usersRef = ref(null);
// 表单重置
function reset() {
  form.value = {
    userid:null,
    name: null,
    username: null,
    password: null,
    role: null,
    startime:null,
    position:null,
    phone:null,
    salary:null,
    email:null
  };
  if (usersRef.value) { // 确保 usersRef 不是 null
    usersRef.value.resetFields();
  }
}


function handleSizeChange(newSize) {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1; // 重置页码为第一页
  getList();
}

function handleCurrentChange(newPage) {
  queryParams.pageNum = newPage;
  getList();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.name = null;
  queryParams.username = null;
  queryParams.phone = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userid);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  fetchpositionsOptions()
  fetchdepartmentOptions()
  reset();
  open.value = true;
  title.value = "添加存储系统用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  fetchpositionsOptions()
  fetchdepartmentOptions()
  const _UserID = row.userid || ids.value
  getUsers(_UserID).then(response => {
    form.value = response;
    open.value = true;
    title.value = "修改存储系统用户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usersRef"].validate(valid => {
    if (valid) {
      if (form.value.userid != null) {
        updateUsers(form.value).then(response => {
          ElMessage({
            message: '修改成功',
            type: 'success'
          }); 
          open.value = false;
          getList();
        });
      } else {
        addUsers(form.value).then(response => {
          ElMessage({
            message: '新增成功',
            type: 'success'
          }); 
          open.value = false;
          getList();
        }).catch(ElMessage({
            message: '检查用户名是否重复',
            type: 'error'
          }));
      }
    }
  });
}

/** 删除按钮操作 */
// 删除按钮操作
function handleDelete(row) {
  const _UserIDs = row.userid || ids.value;
  ElMessageBox.confirm(
    '是否确认删除存储系统用户信息编号为"' + _UserIDs + '"的数据项？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    return delUsers(_UserIDs);
  }).then(() => {
    getList();
    ElMessage({
      message: "删除成功",
      type: "success"
    });
  }).catch(() => {
    ElMessage({
      message: "删除操作已取消",
      type: "info"
    });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/users/export', {
    ...queryParams.value
  }, `users_${new Date().getTime()}.xlsx`)
}




getList();
</script>
<style scoped>
.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-datetime-picker .block:last-child {
  border-right: none;
}
.demo-datetime-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>